package org.gvp.generator.core.channel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;

/**
 * 默认实现写入文件通道
 */
public class DefaultFileWriterChannel implements FileWriterChannel {
    private FileOutputStream os ;
    private FileChannel channel ;

    public DefaultFileWriterChannel(Path filePath) throws FileNotFoundException {
        this.os = new FileOutputStream(filePath.toFile());
        this.channel = os.getChannel();
    }

    @Override
    public void write(String content) {
        try {
            this.channel.write(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            System.err.println("写入文件失败！" + content);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        try {
            this.os.close();
            this.channel.close();
        } catch (IOException e) {
            throw new RuntimeException("关闭文件写入通道失败");
        }
    }
}
